import chalk from "chalk";
import semver from "semver";
import { runCmdSync } from "../utils/runCmd.js";
import {
  getNpmTag,
  npmTagIsAlpha,
  npmTagIsBeta,
  npmTagIsRelease,
  argv,
} from "../utils/npmTag.js";
import pubReleaseQuestion from "../questions/pubReleaseQuestion.js";
import { getPackageJson } from "../utils/getPkgToolsConfig.js";

/**
 * 更新 package.json 版本号
 * @param options
 * @returns {Promise<string|{remoteInfo: {}}>}
 */
const updateVersion = async (options) => {
  console.log("options", options);
  console.log("argv", argv);

  let remoteInfo = {};
  if (!argv["skip-fetch-tags"]) {
    /**
     * 处理 git tag
     * 1. 拉取 git --tags
     * 2. 增加 git tag
     * 3. push git tag
     */

    // 1. 拉取 git --tags
    console.log("git remote -v");
    remoteInfo = runCmdSync("git", ["remote", "-v"], { stdio: "pipe" });
    if (remoteInfo.stdout) {
      console.log("git fetch --tags");
      runCmdSync("git", ["fetch", "--tags"]);
    }
  }

  let customVersion = argv["custom-version"]
  if (customVersion) {
    if (semver.valid(customVersion)) {
      console.log(`npm version ${customVersion} --no-git-tag-version`);
      runCmdSync("npm", [
        "version",
        customVersion,
        "--no-git-tag-version",
      ]);
    } else {
      console.log(chalk.red(`版本号 ${ customVersion } 不符合 semver 规范`));
      process.exit(1);
    }
  } else {
    // 当前为发布先行版本
    if (!npmTagIsRelease()) {
      const npmTag = getNpmTag();
      console.log(`当前发布TAG：${npmTag} 版本，自动生成版本号`);
      if (npmTagIsAlpha()) {
        console.log(
          `npm version prerelease --preid alpha --no-git-tag-version`
        );
        runCmdSync("npm", [
          "version",
          "prerelease",
          "--preid",
          "alpha",
          "--no-git-tag-version",
        ]);
      } else if (npmTagIsBeta()) {
        console.log(`npm version prerelease --preid beta --no-git-tag-version`);
        runCmdSync("npm", [
          "version",
          "prerelease",
          "--preid",
          "beta",
          "--no-git-tag-version",
        ]);
      } else {
        return `未识别的TAG：${npmTag}`;
      }
    } else {
      // 发布正式版本
      const { releaseTag } = await pubReleaseQuestion().catch(() => {
        throw new Error("用户选择了退出");
      });
      console.log(`npm version ${releaseTag} --no-git-tag-version`);
      runCmdSync("npm", ["version", releaseTag, "--no-git-tag-version"]);
    }
  }

  return {
    remoteInfo,
  };
};

export default updateVersion;
